import dbManager from './DatabaseManager';
import { BaseEntity } from './BaseEntity';

/**
 * 数据库初始化器
 * 用于初始化数据库表结构
 */
export class DbInitializer {
  private static instance: DbInitializer;
  private entityClasses: Array<typeof BaseEntity> = [];
  
  private constructor() {}
  
  public static getInstance(): DbInitializer {
    if (!DbInitializer.instance) {
      DbInitializer.instance = new DbInitializer();
    }
    return DbInitializer.instance;
  }
  
  /**
   * 注册实体类
   * @param entityClass 实体类
   */
  public register(entityClass: typeof BaseEntity): DbInitializer {
    this.entityClasses.push(entityClass);
    return this;
  }
  
  /**
   * 初始化所有注册的表
   */
  public initTables(): void {
    const db = dbManager.getDatabase();
    
    try {
      // 创建事务，保证所有表创建的原子性
      const transaction = db.transaction(() => {
        for (const entityClass of this.entityClasses) {
          const createTableSQL = entityClass.getCreateTableSQL();
          console.log(`正在创建表: ${entityClass.getTableInfo().name}`);
          console.log(createTableSQL);
          db.exec(createTableSQL);
        }
      });
      
      transaction();
      console.log('所有表初始化完成');
    } catch (error) {
      console.error('表初始化失败:', error);
      throw error;
    }
  }
}

export default DbInitializer.getInstance(); 